<template>
  <vab-dialog v-model="dialogFormVisible" append-to-body :title="title" width="500px" @close="close">
    <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="名称" prop="name">
        <el-input v-model.trim="form.name" clearable />
      </el-form-item>
      <el-form-item label="上级" prop="pid">
        <el-select v-model="form.pid" placeholder="请选择">
          <el-option :key="0" label="无" :value="0" />
          <el-option v-for="item in formattedOptions" :key="item.menuId" :label="item.name" :value="item.menuId">
            <template v-if="item.level > 0">
              <span v-html="addIndentation(item.name, item.level)"></span>
            </template>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="权限名" prop="permission">
        <el-input v-model.trim="form.permission" clearable />
      </el-form-item>
      <el-form-item label="权重" prop="weight">
        <el-input v-model.trim="form.weight" clearable />
      </el-form-item>
      <el-form-item label="菜单" prop="isMenu">
        <el-switch v-model="form.isMenu" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </vab-dialog>
</template>

<script lang="ts" setup>
import { doMenuEdit as doEdit } from '/@/api/sys'

defineOptions({
  name: 'MenuEdit',
})

const props = defineProps<{
  formattedTreeData: any[]
}>()
const formattedOptions = ref<any[]>([])

const emit = defineEmits(['fetch-data'])
const $baseMessage = inject<any>('$baseMessage')
const formRef = ref<any>(null)
const title = ref<string>('')
const dialogFormVisible = ref<boolean>(false)
const form = reactive<any>({
  name: '',
  pid: 0,
  permission: '',
  weight: '',
  isMenu: 1,
})

const rules = reactive<any>({
  name: [{ required: true, trigger: 'blur', message: '菜单名称不能为空' }],
  pid: [{ required: true, trigger: 'change', message: '上级不能为空' }],
  permission: [{ required: true, trigger: 'blur', message: '权限不能为空' }],
})

// 递归格式化树形结构数据
const formatTree = (data: any[]): any[] => {
  const flatOptions: any[] = []
  const flatten = (data: any[], level: number) => {
    data.forEach((item) => {
      if (item.isMenu == 1) {
        flatOptions.push({
          name: item.name,
          menuId: item.menuId,
          level: level,
        })
        if (item.children && item.children.length > 0) {
          flatten(item.children, level + 1)
        }
      }
    })
  }
  flatten(data, 0)
  return flatOptions
}

const addIndentation = (title: string, level: number): string => {
  const indentation = Array(level).fill('&#12288;').join('')
  return `${indentation}${title}`
}
watch(
  () => props.formattedTreeData,
  (newFormattedTreeData) => {
    // 对新的formattedTreeData进行处理，构造el-select的选项
    formattedOptions.value = formatTree(newFormattedTreeData)
  },
  { deep: true }
)
const showEdit = (row: any) => {
  dialogFormVisible.value = true
  nextTick(() => {
    if (!row) title.value = '添加'
    else {
      title.value = '编辑'
      Object.assign(form, row)
    }
  })
}

defineExpose({
  showEdit,
})

const close = () => {
  formRef.value.clearValidate()
  formRef.value.resetFields()
  emit('fetch-data')
  dialogFormVisible.value = false
}

const save = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      const { message }: any = await doEdit(form)
      $baseMessage(message, 'success', 'hey')
      close()
    }
  })
}
onBeforeMount(() => {})
</script>
